package com.example.tool.web;

import org.springframework.core.io.ClassPathResource;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import shade.com.alibaba.fastjson2.JSONObject;

import java.nio.charset.StandardCharsets;

@RestController
public class RobotsController {
    // 下方 value = "/robots", 决定下方设置机器人消息接收地址，例如：https://example.com/robots
    @RequestMapping(value = "/robots", method = RequestMethod.POST)
    public String helloRobots(@RequestBody(required = false) JSONObject json) {
        System.out.println(json);
        //机器人接收消息内容
        String content = json.getJSONObject("text").get("content").toString().replaceAll(" ", "");

        return content;
    }

    // URL验证
    @GetMapping("/WW_verify_GHiRYxK2fK9XrFKw.txt")
    public String verifyUrl(@RequestParam(value = "echostr", required = false) String echostr) {
        if (echostr != null) {
            // 企业微信URL验证请求
            return echostr;
        } else {
            // 直接访问文件内容
            try {
                ClassPathResource resource = new ClassPathResource("static/WW_verify_GHiRYxK2fK9XrFKw.txt");
                return StreamUtils.copyToString(resource.getInputStream(), StandardCharsets.UTF_8);
            } catch (Exception e) {
                return "File not found";
            }
        }
    }
}